﻿using System.Collections.Generic;

namespace CommonEngine.Tools
{
    /// <summary>
    /// 线程安全集合
    /// </summary>
    public class SafeList<T> : IEnumerable<T> where T : class
    {
        private object Obj = new object();
        List<T> list = new List<T>();

        public void Add(T entity)
        {
            lock (Obj)
                list.Add(entity);
        }

        public int Count()
        {
            lock (Obj)
                return list.Count;
        }

        public void Clear()
        {
            lock (Obj)
                list.Clear();
        }

        public void Remove(T item)
        {
            lock (Obj)
                if (list.Count > 0)
                    list.Remove(item);
        }

        public IEnumerator<T> GetEnumerator()
        {
            lock (Obj)
                foreach (var v in list)
                    yield return v;
        }

        System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator()
        {
            return this.GetEnumerator();
        }
    }
}
